import io from 'socket.io-client'
import store from '@/store/index'
import { postImage, getUploadToken } from '@/utils/api'
class SocketIO {
  constructor (url, path) {
    this.url = url
    this.path = path
    this.socket = null
    this.connect()
  }

  connect () {
    this.socket = io(this.url, { path: this.path })
    this.socket.on('connect', () => {
      store.commit('SET_NET_STATE', 'connected')
    })
    this.socket.on('disconnect', reason => {
      if (reason === 'io server disconnect') {
        store.commit('SET_NET_STATE', 'server_disconnect')
      } else {
        store.commit('SET_NET_STATE', 'network_error')
      }
    })
    this.socket.on('control', () => {
      this.socket.emit('username', store.state.user)
    })
    this.socket.on('chatmessage', ({ user, message, dtype, data }) => {
      store.commit('ADD_MESSAGE', { user, message, dtype, data })
    })
    window.setTimeout(() => {
      if (!this.socket.connected) store.commit('SET_NET_STATE', 'network_error')
    }, 3000)
  }

  async sendMessage (user, message, dtype, data) {
    if (dtype === 'image') {
      try {
        var res = await getUploadToken()
        res = res.data
        if (!res.success) throw res
        var uploadtoken = res.data.uploadtoken
        var uploadurl = res.data.uploadurl
        var cdnurl = res.data.cdnurl
        res = await postImage(data, uploadtoken, uploadurl)
        var src = cdnurl + res.data.key
        this.socket.emit('chatmessage', { user, message, dtype: dtype, data: src })
      } catch (err) {
        var errmsg = 'unknown err'
        if (err.response && err.response.status) errmsg = 'qiniu unavailable now'
        else if (err.message) errmsg = err.message
        store.commit('ADD_MESSAGE', { user: 'system', message: errmsg })
      }
    } else {
      this.socket.emit('chatmessage', { user, message, dtype: dtype || 'text', data: data || null })
    }
  }
}

export default SocketIO
